from django.shortcuts import render

# Create your views here.
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from goods.models import GoodsCategory, SKU, SKUComments, Goods
from goods.serializers import CategoriesListSerializer, SKUSearchSerializer, SKUHistorSerializer
from rest_framework.pagination import PageNumberPagination

from orders.models import OrderGoods


class ListPageNumber(PageNumberPagination):
    '''分页器'''
    page_size_query_param = 'page_size'
    max_page_size = 10


class CategoriesView(APIView):

    def get(self, request, pk):
        # 通过三级id获取二级和一级id
        try:
            cat3 = GoodsCategory.objects.get(id=pk)
        except:
            return Response({'error': '没有此分类'})

        cat2 = GoodsCategory.objects.get(id=cat3.parent.id)
        cat1 = GoodsCategory.objects.get(id=cat2.parent.id)

        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name,
        })


class CategoriesListView(ListAPIView):
    serializer_class = CategoriesListSerializer
    pagination_class = ListPageNumber
    filter_backends = [OrderingFilter]
    ordering_fields = ['create_time', 'price', 'sales']

    def get_queryset(self):
        return SKU.objects.filter(category=self.kwargs['pk'])


class SKUSearchViewSet(HaystackViewSet):
    index_models = [SKU]
    serializer_class = SKUSearchSerializer
    pagination_class = ListPageNumber


class SKUHistoryView(CreateAPIView):
    """保存用户浏览记录"""
    serializer_class = SKUHistorSerializer

    def get(self, request):
        user = request.user
        conn = get_redis_connection('history')

        sku_ids = conn.lrange('history_%s' % user.username, 0, 5)
        skus = SKU.objects.filter(id__in=sku_ids)

        ser = CategoriesListSerializer(skus, many=True)
        return Response(ser.data)


class CommentsListView(ListAPIView):
    """http://api.meiduo.site:8000/skus/16/comments/"""
    def get_queryset(self):

        orders = OrderGoods.objects.filter(sku_id=self.kwargs['pk'], is_commented=True)
        return orders

    def get(self, request, *args, **kwargs):

        # 返回用户名, comment,score
        # 获取good_id对应评论数据
        orders = self.get_queryset()
        comments = []
        for order in orders:
            comment = {}
            comment['comment'] = order.comment
            comment['username'] = order.order.user.username
            comment['score'] = order.score
            if order.is_anonymous:
                comment['username'] = comment['username'][0]+'***'+comment['username'][-1]
            comments.append(comment)
        return Response(comments)


class UncommentsView(ListAPIView):
    """orders/(?P<order_id>\d+)/uncommentgoods/"""
    def get_queryset(self):
        order_goods = OrderGoods.objects.filter(order_id=self.kwargs['order_id'])
        return order_goods

    def get(self, request, *args, **kwargs):
        order_goods = self.get_queryset()

        orders = []
        for order_good in order_goods:
            sku = {}
            sku['sku'] = {
                'name': order_good.sku.name
            }
            sku['price'] = order_good.sku.price
            sku['default_image_url'] = order_good.sku.default_image_url
            orders.append(sku)
        return Response(orders)


class CommentsView(UpdateAPIView):

    # serializer_class = CommentsListSerializer

    def get_queryset(self):
        try:
            order_good = OrderGoods.objects.get(order_id=self.kwargs['order_id'])
        except:
            return Response({'error': '无此用户'})
        return order_good

    def post(self, request, *args, **kwargs):
        order_good = self.get_queryset()
        comment = request.POST.get('comment')
        score = request.POST.get('score')
        is_commented = request.POST.get('is_commented')
        is_anonymous = request.POST.get('is_anonymous')

        # order_good.objects.update({'comment':comment, 'score':score,
        #                           'is_commented':is_commented, 'is_anonymous':is_anonymous})
        # order_good.comment = comment
        # order_good.score = score
        # order_good.is_commented = is_commented
        # order_good.is_anonymous = is_anonymous
        data = {'comment': comment, 'score': score,
                'is_commented': is_commented, 'is_anonymous': is_anonymous}
        order_good.__dict__.update(**data)

        return Response({'massage': 'ok'})


